//
//  EditTypeViewController.m
//  CS Inventory Manager
//
//  Created by Billy Zoellers on 3/25/13.
//  Copyright (c) 2013 Transylvania University. All rights reserved.
//

#import "EditTypeViewController.h"
#import "TypeViewController.h"

@interface EditTypeViewController ()

@end

@implementation EditTypeViewController
@synthesize theType,delegate,inManufacturer,inName;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (IBAction)saveButton:(id)sender {
    
    //Error checking: make sure both fields are filled in
    if ((inName.text.length != 0) && (inManufacturer.text.length != 0)) {
        // add data locally
        [theType setName:inName.text];
        [theType setManufacturer:inManufacturer.text];
        
        // generate the URL and use %20 encoding
        NSString *urlStr = [NSString stringWithFormat:@"http://www.cs.transy.edu/zoellers/inventory/type.php?secret=pass&id=%d&name=%@&manu=%@&cat=%d",[theType typeId], [theType name], [theType manufacturer],[[delegate category] catId]];
        NSString *final = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        NSLog(@"The url is: >>>>>%@<<<<<", final);
        
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:final]];
        
        // make web request and catch error
        NSError * e;
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&e];
        
        // log the value returned from the web server
        NSString *value = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"return from web: %@", value);
        
        // is this a save or edit?
        if ([theType typeId] == 0) {
            // get the auto_increment value from web (if new)
            int newCatID = [[[value componentsSeparatedByString:@"*"] objectAtIndex:1] integerValue];
            NSLog(@"Got back from web: %i", newCatID);
            
            // adding a new category
            [theType setTypeId:newCatID];
            
            // add the patron the array AFTER we have created it
            [[[self.delegate category] types] addObject:theType];
        }
        
        [[delegate tableView] reloadData];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (IBAction)cancelButton:(id)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - Text Field Delegate
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
    
    if (theTextField == inManufacturer) {
        [inName becomeFirstResponder];
    } else if (theTextField == inName) {
        [inName resignFirstResponder];
    }
    
    return YES;
}


- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    // Return the number of rows in the section.
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *CellIdentifier = @"editTypeCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    cell.detailTextLabel.text = @"";
    
    // make a text field
    UITextField *inputTextField = [[UITextField alloc] initWithFrame:CGRectMake(85, 10, 395, 30)];
    inputTextField.adjustsFontSizeToFitWidth = YES;
    inputTextField.textColor = [UIColor blackColor];
    inputTextField.backgroundColor = [UIColor clearColor];
    inputTextField.autocorrectionType = UITextAutocorrectionTypeDefault;
    inputTextField.autocapitalizationType = UITextAutocapitalizationTypeWords;
    inputTextField.tag = 0;
    inputTextField.clearButtonMode = UITextFieldViewModeAlways;
    [inputTextField setEnabled: YES];
    inputTextField.delegate = self;
    
    switch (indexPath.row) {
        case 0:
            cell.textLabel.text = @"Manufacturer";
            inputTextField.text = [theType manufacturer];
            inputTextField.returnKeyType = UIReturnKeyNext;
            self.inManufacturer = inputTextField;
            [cell.contentView addSubview:inputTextField];
            inputTextField = nil;
            
            break;
        case 1:
            cell.textLabel.text = @"Name";
            inputTextField.text = [theType name];
            inputTextField.returnKeyType = UIReturnKeyDone;
            self.inName = inputTextField;
            [cell.contentView addSubview:inputTextField];
            inputTextField = nil;
            
            break;
    }
    
    return cell;
}

@end
